package com.fin.quant.domain.service.impl;

import com.fin.quant.domain.entity.AssetEntity;
import com.fin.quant.domain.mapstruct.AssetMapperStruct;
import com.fin.quant.domain.service.AssetDaoService;
import com.fin.quant.domain.vo.GetAssetsQuery;
import com.fin.quant.instra.mysql.mapper.AssetMapper;
import com.fin.quant.instra.mysql.model.Asset;
import com.fin.quant.instra.mysql.model.AssetExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 资产领域服务实现
 */
@Service
public class AssetDaoServiceImpl implements AssetDaoService {

    @Autowired
    private AssetMapper assetMapper;

    @Override
    public List<AssetEntity> getAll() {
        AssetExample example = new AssetExample();
        List<Asset> assets = assetMapper.selectByExample(example);
        return assets.stream().map(AssetMapperStruct.INSTANCE::model2Entity).collect(Collectors.toList());
    }

    @Override
    public AssetEntity findById(Long assetId) {
        Asset asset = assetMapper.selectByPrimaryKey(assetId);
        return AssetMapperStruct.INSTANCE.model2Entity(asset);
    }


    @Override
    public List<AssetEntity> findAssets(GetAssetsQuery getAssetsQuery) {
        AssetExample example = new AssetExample();
        AssetExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(getAssetsQuery.getAssetCode())) {
            criteria.andAssetCodeEqualTo(getAssetsQuery.getAssetCode());
        }
        if (StringUtils.isNotBlank(getAssetsQuery.getAssetType())) {
            criteria.andAssetTypeEqualTo(getAssetsQuery.getAssetType());
        }
        if (StringUtils.isNotBlank(getAssetsQuery.getSector())) {
            criteria.andSectorEqualTo(getAssetsQuery.getSector());
        }
        if (StringUtils.isNotBlank(getAssetsQuery.getMarket())) {
            criteria.andMarketEqualTo(getAssetsQuery.getMarket());
        }
        if (StringUtils.isNotBlank(getAssetsQuery.getAssetName())) {
            criteria.andAssetNameLike("%" + getAssetsQuery.getAssetName() + "%");
        }
        if (StringUtils.isNotBlank(getAssetsQuery.getSortOrder())) {
            if ("asc".equals(getAssetsQuery.getSector())) {
                example.setOrderByClause("id asc");
            } else {
                example.setOrderByClause("id desc");
            }
        } else {
            example.setOrderByClause("id asc");
        }

        List<Asset> assets = assetMapper.selectByExample(example);
        return assets.stream().map(AssetMapperStruct.INSTANCE::model2Entity).collect(Collectors.toList());
    }


}
